package com.zstu.mall.service.impl;

import com.zstu.mall.dao.*;
import com.zstu.mall.entity.*;
import com.zstu.mall.service.LoggingService;
import com.zstu.mall.service.ShopCartService;
import com.zstu.mall.service.exception.LoginException;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.zstu.mall.common.BaseServiceImpl;
import com.zstu.mall.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author     : wuyc
 * @description: OrderServiceImpl
 * @date       : Created in 2019/11/24
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl<Order, String, OrderDao> implements OrderService {

	@Autowired
	private OrderDao orderDao;

	@Autowired
	private ProductDao productDao;

	@Autowired
	private UserOrderDao userOrderDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private LoggingService loggingService;

	/**
	 * 查询订单项详情
	 * @param orderId
	 * @return
	 */
	@Override
	public List<UserOrder> findItems(String orderId) {
		List<UserOrder> list = userOrderDao.findByOrderId(orderId);
		for (UserOrder orderItem : list) {
			if(productDao.existsById(orderItem.getProductId()) == true){
				Product product = productDao.getOne(orderItem.getProductId());
				orderItem.setProduct(product);
			}
		}
		return list;
	}

	/**
	 * 更改订单状态
	 *
	 * @param id
	 * @param status
	 */
	@Override
	@Transactional
	public void updateStatus(String id, String status) {
		if(orderDao.existsById(id) == true){
			Order order = orderDao.getOne(id);
			order.setStatus(status);
			order.setGmtModified(new Date());
			orderDao.save(order);
		}
	}

	/**
	 * 查找用户的订单列表
	 *
	 * @param request
	 * @return
	 */
	@Override
	public List<Order> findUserOrder(HttpServletRequest request) {
		//从session中获取登录用户的id，查找他的订单
		Object user = request.getSession().getAttribute("user");
		if (user == null)
			throw new LoginException("请登录！");
		User loginUser = (User) user;
		List<Order> orders = orderDao.findByUserId(loginUser.getId());
		return orders;
	}

	/**
	 * 支付
	 * @param id
	 * @param name
	 * @param payPassword
	 */
	@Override
	@Transactional//加入事务
	public void pay(String id, String name, String payPassword) {
		User user = userDao.findByNameAndPaypassword(name, payPassword);
		//具体逻辑就不实现了，直接更改状态为 待发货
		if (orderDao.existsById(id) == false)
			throw new RuntimeException("订单不存在");
		else if(user == null)
			throw new RuntimeException("支付密码不正确");
		else {
			Order order = orderDao.getOne(id);
			order.setStatus(STATUS_WAITE_SEND);
            List<UserOrder> userOrders = userOrderDao.findByOrderId(id);
            for (UserOrder userOrder : userOrders) {
                userOrder.setStatus(STATUS_WAITE_SEND);
                userOrder.setGmtModified(new Date());
                userOrderDao.save(userOrder);
            }
			orderDao.updateStatus(STATUS_WAITE_SEND,id);
		}
	}

	/**
	 * 提交订单
	 * @param ids
	 * @param request
	 * @param response
	 */
	@Override
	@Transactional
	public void submit(List<String> ids, HttpServletRequest request, HttpServletResponse response) throws Exception{
		Object user = request.getSession().getAttribute("user");
		if (user == null)
			throw new LoginException("请登录！");
		User loginUser = (User) user;
		Order order = new Order();
		order.setId(createId());
		order.setUserId(loginUser.getId());
		//默认信息
		order.setName(loginUser.getName());
		order.setPhone(loginUser.getTelephone());
		order.setAddr(loginUser.getAddress1());
		//设置为未确认
		order.setStatus(STATUS_NO_CONFIRM);
		List<UserOrder> userOrders = new ArrayList<>();
		for(String id : ids){
			userOrders.add(userOrderDao.getOne(id));
		}
		Double total = 0.0;
		Double string1 = 0.0;
		String product = "";
		String activity = "";
		for (UserOrder userOrder : userOrders) {
			product = userOrder.getProductId() + ",";
			activity = productDao.getOne(userOrder.getProductId()).getActivityId() + ";";
			total += userOrder.getTotal();//折后
			string1 += Double.parseDouble(userOrder.getString1());//原价
			userOrder.setOrderId(order.getId());
			//设置为待确认
			userOrder.setStatus(STATUS_NO_CONFIRM);
			userOrder.setGmtModified(new Date());
			userOrderDao.save(userOrder);
		}
		//移除最后一个,
		product = product.substring(0, product.length()-1);
		activity = activity.substring(0, activity.length()-1);
		//折后
		order.setTotal(total);
		//原价
		order.setString1(String.valueOf(string1));
		orderDao.save(order);
		loggingService.createLog(loggingService.createId(), loginUser.getId(), product, activity,"提交订单");
		//告诉ajax我是重定向
		response.setHeader("REDIRECT", "REDIRECT");
		//告诉ajax我重定向的路径
		response.setHeader("CONTENTPATH", "/mall/order/toConfirm.html?id="+order.getId());
		response.flushBuffer();
		//重定向到订单确认页面
		//response.sendRedirect("/mall/order/toConfirm.html?id="+order.getId());
	}

	/**
	 * 确认订单
	 * @param id
	 * @param name
	 * @param phone
	 * @param addr
	 * @param request
	 * @param response
	 */
	@Override
	@Transactional
	public void confirm(String id, String name, String phone, String addr, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Object user = request.getSession().getAttribute("user");
		if (user == null)
			throw new LoginException("请登录！");
		User loginUser = (User) user;
		Order order = orderDao.getOne(id);
		//设置为未支付 张：这里我就直接设置为支付了
		order.setStatus(STATUS_WAITE_SEND);
		List<UserOrder> userOrders = userOrderDao.findByOrderId(id);
		String product = "";
		String activity = "";
		for (UserOrder userOrder : userOrders) {
			product += userOrder.getProductId() + ",";
			activity += productDao.getOne(userOrder.getProductId()).getActivityId() + ";";
			//设置为待支付
			userOrder.setStatus(STATUS_WAITE_SEND);
			userOrderDao.save(userOrder);
		}
		//移除最后一个,
		product = product.substring(0, product.length()-1);
		activity = activity.substring(0, activity.length()-1);
		orderDao.save(order);
		loggingService.createLog(loggingService.createId(), loginUser.getId(), product, activity,"确认支付");
		/*//告诉ajax我是重定向
		response.setHeader("REDIRECT", "REDIRECT");
		//告诉ajax我重定向的路径
		response.setHeader("CONTENTPATH", "/mall/order/toPay.html?id="+order.getId());
		response.flushBuffer();
		//重定向到支付页面
//		response.sendRedirect("/mall/order/toPay.html?id="+order.getId());*/
	}

	/**
	 * 确认收货
	 *
	 * @param orderId
	 */
	@Override
	@Transactional
	public void receive(String orderId) {

		if (orderDao.existsById(orderId) == false)
			throw new RuntimeException("订单不存在");
		else {
			Order order = orderDao.getOne(orderId);
            List<UserOrder> userOrders = userOrderDao.findByOrderId(orderId);
            for (UserOrder userOrder : userOrders) {
                userOrder.setStatus(STATUS_COMPLETE);
                userOrderDao.save(userOrder);
            }
            orderDao.updateStatus(STATUS_COMPLETE,order.getId());
		}
	}

}
